<template>
  <div>
    <!-- <img src='./dianli16.svg'/> -->
    <a-form :model="queryForm" style="border: 1px solid #f0f0f0; border-radius: 8px; background: #ffffff; font-size: 14px; margin-bottom: 10px">
      <a-form-item label="登录账号" style="margin: 10px">
        <a-input style="width: 200px" v-model:value="queryForm.username" />
        <a-button type="primary" style="margin: 0 10px" @click="queryTable">查询</a-button>
      </a-form-item>
    </a-form>
    <a-row :gutter="16" class="height100">
      <a-col :span="6">
        <a-card class="tree-container" size="small">
          <a-directory-tree
            v-model:expandedKeys="expandedKeys"
            v-model:selectedKeys="selectedKeys"
            multiple
            :fieldNames="{ title: 'title', key: 'key', value: 'key' }"
            :tree-data="treeData"
            :defaultExpandAll="true"
            @select="treeSelectChange"
          ></a-directory-tree>
        </a-card>
      </a-col>
      <a-col :span="18" class="height100">
        <div class="help-doc-box height100">
          <a-card class="tree-container" size="small">
            <div class="smart-table-operate-block" style="display: flex">
              <a-button type="primary" style="size: small" @click="add">新增</a-button>
              <a-button type="primary" @click="confirmBatchDelete">
                <template #icon>
                  <DownloadOutlined />
                </template>
                下载模板
              </a-button>
              <a-button type="primary" @click="passwordReset">密码重置</a-button>
              <a-button type="primary" danger @click="deletes()" :disabled="selectedRowKeyList.length == 0">批量删除</a-button>
              <a-button @click="onExportGoods">
                <template #icon>
                  <ExportOutlined />
                </template>
                导出
              </a-button>

              <a-upload
                v-model:fileList="fileList"
                name="excelFile"
                :multiple="false"
                action="/maxkey-mgt-api/users/import"
                accept=".xls,.xlsx"
                @change="handleChange"
                :show-upload-list="false"
                :headers="headers"
              >
                <a-button>
                  <upload-outlined />
                  导入
                </a-button>
              </a-upload>
            </div>
            <a-table
              bordered
              rowKey="id"
              :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }"
              :dataSource="dataSource"
              :columns="columns"
              :pagination="false"
              :scroll="{ x: 800 }"
            >
              <template #bodyCell="{ column, record }">
                <!-- 性别 -->
                <template v-if="column.key === 'gender'">
                  <div>{{ record.gender == 1 ? '男' : '女' }}</div>
                </template>
                <template v-if="column.key === 'action'">
                  <!-- 状态图标 -->
                  <span v-if="record.status == 1">
                    <!-- 启用 -->
                    <check-circle-two-tone two-tone-color="#52c41a" />
                  </span>
                  <span v-if="record.status == 2">不活跃</span>
                  <span v-if="record.status == 3">启用</span>
                  <!-- 禁用 -->
                  <span v-if="record.status == 4">
                    <CloseCircleFilled />
                  </span>
                  <!-- 锁定 -->
                  <span v-if="record.status == 5">
                    <LockFilled />
                  </span>
                </template>
                <!-- 操作 -->
                <template v-if="column.key === 'status'">
                  <a-button type="link" @click="edit(record)">编辑</a-button>
                  <a-dropdown>
                    <a class="ant-dropdown-link">
                      操作
                      <DownOutlined />
                    </a>
                    <template #overlay>
                      <a-menu>
                        <a-menu-item v-if="record.status != 5 && record.status != 4">
                          <a-button type="link" @click="accounts">账号</a-button>
                        </a-menu-item>
                        <a-menu-item v-if="record.status != 5 && record.status != 4">
                          <a-button type="link" @click="toRoles(record)">角色</a-button>
                        </a-menu-item>
                        <a-menu-item v-if="record.status != 5 && record.status != 4">
                          <a-button type="link" @click="showModal">岗位</a-button>
                        </a-menu-item>
                        <a-menu-item v-if="record.status != 5 && record.status != 4">
                          <a-button type="link" @click="parttime">兼职</a-button>
                        </a-menu-item>
                        <a-menu-item v-if="record.status != 5 && record.status != 4">
                          <a-button type="link" @click="modify">密码修改</a-button>
                        </a-menu-item>
                        <a-menu-item v-if="record.status != 5 && record.status != 4">
                          <a-button type="link" @click="locks(record)">锁定</a-button>
                        </a-menu-item>
                        <a-menu-item v-if="record.status != 5 && record.status != 4">
                          <a-button type="link" @click="Disables(record)">禁用</a-button>
                        </a-menu-item>
                        <a-menu-item v-if="record.status == 4">
                          <a-button type="link" @click="unlocks(record)">启用</a-button>
                        </a-menu-item>
                        <a-menu-item v-if="record.status == 5">
                          <a-button type="link" @click="unlock(record)">解锁</a-button>
                        </a-menu-item>
                        <a-menu-item>
                          <a-button danger type="text" @click="deletes(record)">删除</a-button>
                        </a-menu-item>
                      </a-menu>
                    </template>
                  </a-dropdown>
                </template>
              </template>
            </a-table>
            <!-- 岗位编辑弹框 -->
            <a-modal v-model:open="open" title="编辑" @ok="handleOk3" style="width: 800px">
              <a-form :model="formStatePositions" :label-col="labelCol" :wrapper-col="wrapperCol" style="display: flex">
                <a-form-item label="岗位名称:">
                  <a-input v-model:value="formStatePositions.Positionname" />
                </a-form-item>
                <a-form-item label="状态">
                  <a-select @change="handleSelectChange" v-model:value="formStatePositions.assign" placeholder="拥有" style="width: 150px">
                    <a-select-option value="owns">拥有</a-select-option>
                    <a-select-option value="assignable">可分配</a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item style="margin-left: 50px">
                  <a-button type="primary" @click="queryTable2">查询</a-button>
                </a-form-item>
              </a-form>
              <a-table :dataSource="dataSources" :columns="columnss" bordered :pagination="false">
                <template #bodyCell="{ column, record, text, index }">
                  <template v-if="column.title === '操作'">
                    <a-button v-if="formStatePositions.assign === 'assignable'" @click="handleAdd(record)">新增</a-button>
                  
                      <a-button v-else danger @click="handleEditor(record.id)">删除</a-button>
               
                    
                  </template>
                  <template v-if="column.key === 'instId'">
                    <!-- 启用 -->
                    <check-circle-two-tone two-tone-color="#52c41a" />
                  </template>
                </template>
              </a-table>
              <!-- 岗位表格分页组件 -->
              <div style="float: right; margin-top: 12px">
                <a-pagination
                  v-model:current="formStatePositions.pageNumber"
                  v-model:page-size="formStatePositions.pageSize"
                  :page-size-options="pageSizeOptions2"
                  :total="total2"
                  show-size-changer
                  @showSizeChange="onShowSizeChange2"
                  @change="onPageChange2"
                ></a-pagination>
              </div>
            </a-modal>
            <!-- 用户管理table分页组件 -->
            <div style="float: right; right: 10px">
              <a-pagination
                v-model:current="queryForm.pageNumber"
                v-model:page-size="queryForm.pageSize"
                :page-size-options="pageSizeOptions"
                :total="total"
                show-size-changer
                @showSizeChange="onShowSizeChange"
                @change="onPageChange"
                :show-total="(total) => `共${total}条`"
              ></a-pagination>
            </div>
          </a-card>
        </div>
      </a-col>
    </a-row>

    <a-modal
      v-model:visible="visible"
      :title="title"
      @ok="handleOk2"
      :okText="okButtonText"
      :cancelText="cancelButtonText"
      @cancel="handleCancel"
      style="width: 800px"
    >
      <!-- form表单内容 -------------------------------------------->
      <a-form
        :model="formState"
        name="basic"
        ref="formRef1"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 16 }"
        :rules="rules"
        autocomplete="off"
        @finish="onFinish"
        @finishFailed="onFinishFailed"
      >
        <a-tabs v-model:activeKey="activeKey">
          <a-tab-pane key="1" tab="基本信息">
            <a-row>
              <a-col :span="12">
                <a-form-item label="姓名" name="displayName" :rules="[{ required: true, message: '姓名不能为空' }]">
                  <a-input v-model:value="formState.displayName" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="性别">
                  <a-radio-group v-model:value="formState.gender">
                    <a-radio value="1">男</a-radio>
                    <a-radio value="2">女</a-radio>
                  </a-radio-group>
                </a-form-item>
              </a-col>

              <a-col :span="12">
                <a-form-item label="登录账号" name="username" :rules="[{ required: true, message: '登录账号不能为空' }]">
                  <a-input v-model:value="formState.username" />
                </a-form-item>
              </a-col>

              <a-col :span="12">
                <a-form-item label="员工编号">
                  <a-input v-model:value="formState.employeeNumber" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="手机号码">
                  <a-input v-model:value="formState.mobile" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="用户类型" name="userType">
                  <a-select v-model:value="formState.userType" placeholder="内部员工">
                    <a-select-option :value="1">内部员工</a-select-option>
                    <a-select-option :value="2">供应商</a-select-option>
                    <a-select-option :value="3">客户</a-select-option>
                    <a-select-option :value="4">承包商</a-select-option>
                    <a-select-option :value="5">经销商</a-select-option>
                    <a-select-option :value="6">合作伙伴</a-select-option>
                    <a-select-option :value="7">外部用户</a-select-option>
                    <a-select-option :value="8">实习生</a-select-option>
                    <a-select-option :value="9">临时用户</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="12">
                <a-form-item label="域账号">
                  <a-input v-model:value="formState.windowsAccount" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="用户状态" name="userState">
                  <a-select v-model:value="formState.userState">
                    <a-select-option :value="1">在职</a-select-option>
                    <a-select-option :value="2">离职</a-select-option>
                    <a-select-option :value="3">停薪留职</a-select-option>
                    <a-select-option :value="4">退休</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="排序" name="sort" :rules="[{ required: true, message: '排序不能为空' }]">
                  <a-input v-model:value="formState.sort" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="状态" name="online">
                  <a-select v-model:value="formState.online">
                    <a-select-option :value="1">活动</a-select-option>
                    <a-select-option :value="2">不活动</a-select-option>
                    <a-select-option :value="3">禁用</a-select-option>
                    <a-select-option :value="4">锁定</a-select-option>
                    <a-select-option :value="5">已删除</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="电子邮箱">
                  <a-input v-model:value="formState.email" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-tab-pane>
          <!-- ----------------------------------------------- -->
          <a-tab-pane key="2" tab="个人信息" force-render>
            <a-row>
              <a-col :span="12">
                <a-form-item label="姓：">
                  <a-input v-model:value="formState.familyName" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="中间名：">
                  <a-input v-model:value="formState.middlename" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="名：">
                  <a-input v-model:value="formState.givenName" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="昵称：">
                  <a-input v-model:value="formState.nickName" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="证件类型">
                  <a-select v-model:value="formState.idType" placeholder="身份证">
                    <a-select-option :value="0">未知</a-select-option>
                    <a-select-option :value="1">身份证</a-select-option>
                    <a-select-option :value="2">护照</a-select-option>
                    <a-select-option :value="3">学生证</a-select-option>
                    <a-select-option :value="4">军人证</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="证件号码：">
                  <a-input v-model:value="formState.idCardNo" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="婚姻状态">
                  <a-select v-model:value="formState.married" placeholder="请选择婚姻状态">
                    <a-select-option :value="0">未知</a-select-option>
                    <a-select-option :value="1">单身</a-select-option>
                    <a-select-option :value="2">已婚</a-select-option>
                    <a-select-option :value="3">离异</a-select-option>
                    <a-select-option :value="4">丧偶</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="出生日期：">
                  <a-input v-model:value="formState.birthDate" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="学历：">
                  <a-input v-model:value="formState.education" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="毕业院校：">
                  <a-input v-model:value="formState.graduateFrom" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="毕业时间：" name="graduateDate">
                  <a-date-picker v-model:value="formState.graduateDate" show-time type="date" placeholder="请选择毕业时间" style="width: 100%" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="出生日期：" name="graduateDate">
                  <a-date-picker v-model:value="formState.graduateDate" show-time type="date" placeholder="请选择出生时间" style="width: 100%" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="时区：">
                  <a-input v-model:value="formState.timeZone" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="语言偏好：">
                  <a-input v-model:value="formState.preferredLanguage" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="个人主页：">
                  <a-input v-model:value="formState.webSite" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="即时通讯：">
                  <a-input v-model:value="formState.definelm" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-tab-pane>
          <!-- ---------------------------------------------- -->
          <a-tab-pane key="3" tab="机构信息">
            <a-row>
              <a-col :span="12">
                <a-form-item label="所属组织：">
                  <a-input v-model:value="formState.organization" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="分支机构：">
                  <a-input v-model:value="formState.division" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="部门编号">
                  <a-input v-model:value="formState.departmentId" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="部门名称">
                  <a-select v-model:value="formState.department" :options="departmentOptions"></a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="成本中心：">
                  <a-input v-model:value="formState.costCenter" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="级别：">
                  <a-input v-model:value="formState.jobLevel" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="职位：">
                  <a-input v-model:value="formState.jobTitle" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="上级经理：">
                  <a-input v-model:value="formState.manager" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="助理：">
                  <a-input v-model:value="formState.assistant" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="办公地址：">
                  <a-input v-model:value="formState.workOfficeName" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="入职时间：" name="entryDate">
                  <a-date-picker v-model:value="formState.entryDate" show-time type="date" placeholder="请选择入职时间" style="width: 100%" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="离职时间：" name="quitDate">
                  <a-date-picker v-model:value="formState.quitDate" show-time type="date" placeholder="请选择离职时间" style="width: 100%" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-tab-pane>
          <!-- ----------------------------------------- -->
          <a-tab-pane key="4" tab="机构扩展">
            <a-row>
              <a-col :span="12">
                <a-form-item label="工作电话：">
                  <a-input v-model:value="formState.workPhoneNumber" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="工作邮件：">
                  <a-input v-model:value="formState.workEmail" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="国家：">
                  <a-input v-model:value="formState.homeCountry" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="省：">
                  <a-input v-model:value="formState.homeRegion" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="城市：">
                  <a-input v-model:value="formState.workLocality" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="地址：">
                  <a-input v-model:value="formState.workStreetAddress" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="邮箱">
                  <a-input v-model:value="formState.email" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="传真">
                  <a-input v-model:value="formState.workFax" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-tab-pane>
          <a-tab-pane key="5" tab="家庭信息">
            <a-row>
              <a-col :span="12">
                <a-form-item label="家庭邮箱：">
                  <a-input v-model:value="formState.homeEmail" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="家庭电话:" placeholder="13817378313">
                  <a-input v-model:value="formState.homePhoneNumber" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="家庭传真：">
                  <a-input v-model:value="formState.homeFax" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="家庭邮编：">
                  <a-input v-model:value="formState.homePostalCode" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="国家：">
                  <a-input v-model:value="formState.workCountry" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="省：">
                  <a-input v-model:value="formState.workRegion" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="城市">
                  <a-input v-model:value="formState.homeLocality" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="家庭地址">
                  <a-input v-model:value="formState.homeStreetAddress" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-tab-pane>
          <a-tab-pane key="6" tab="自定义字段">
            <a-form-item label="学历" style="margin-right: 150px">
              <a-input v-model:value="formState.education" />
            </a-form-item>
            <a-form-item label="毕业院校" style="margin-right: 150px">
              <a-input v-model:value="formState.graduateFrom" />
            </a-form-item>
            <a-form-item label="毕业日期" style="margin-right: 150px">
              <a-input v-model:value="formState.graduateDate" />
            </a-form-item>
          </a-tab-pane>
        </a-tabs>
      </a-form>
    </a-modal>

    <!-- 密码修改弹框 -->
    <a-modal
      v-model:visible="visible1"
      title="密码修改"
      @ok="handleOk()"
      :okText="okButtonText"
      :cancelText="cancelButtonText"
      @cancel="handleCancel"
      style="width: 650px"
    >
      <a-form
        :model="passwordFormState"
        name="basic"
        ref="formRef"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        :rules="rules"
        layout="horizontal"
        style="max-width: 600px"
        autocomplete="off"
        @finish="onFinish"
        @finishFailed="onFinishFailed"
        :disabled="componentDisabled"
      >
        <a-form-item label="登录账号:" :rules="[{ required: true, message: '登录账号不能为空' }]">
          <a-input v-model:value="passwordFormState.username" />
        </a-form-item>
        <a-form-item label="姓名:" :rules="[{ required: true, message: '姓名不能为空' }]">
          <a-input v-model:value="passwordFormState.displayName" />
        </a-form-item>
      </a-form>
      <a-form
        :model="passwordFormState"
        name="basic"
        ref="formRef"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 16 }"
        :rules="rules"
        autocomplete="off"
        @finish="onFinish"
        @finishFailed="onFinishFailed"
      >
        <div style="display: flex; margin-left: 8px">
          <a-form-item style="width: 430px" label="新密码" name="newpassword" :rules="[{ required: true, message: '新密码不能为空' }]">
            <a-input-password placeholder="new password" v-model:value="passwordFormState.newpassword" />
          </a-form-item>
          <a-button @click="generatePassword" type="primary">生成</a-button>
        </div>
        <a-form-item style="width: 460px" label="确认密码" name="password" :rules="[{ required: true, message: '确认密码不能为空' }]">
          <a-input-password visibilityToggle="false" placeholder="confirm password" v-model:value="passwordFormState.password" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
  <Parttimeform ref="ParttimeformRef" />
</template>
<script setup>
  import { reactive, ref, onMounted } from 'vue';
  import { useRouter } from 'vue-router';
  import { message, Modal } from 'ant-design-vue';
  import { userApi } from '/src/api/system/user.js';
  import { localRead } from '/@/utils/local-util';
  import LocalStorageKeyConst from '/@/constants/local-storage-key-const.js';
  // 兼职弹框组件导入
  import Parttimeform from './components/parttime-form.vue';

  const title = ref('');
  const treeData = ref([]);
  const dataSource = ref([]);
  const current = ref(1);
  const pageSizeRef = ref(6);
  const componentDisabled = ref(true);
  const departmentOptions = ref([]);
  // 选择表格行
  const selectedRowKeyList = ref([]);
  // 用来存表格行数据
  const selectRecords = ref([]);
  function onSelectChange(selectedRowKeys, records) {
    selectedRowKeyList.value = selectedRowKeys;
    selectRecords.value = records;
  }
  const labelCol = {
    style: {
      width: '150px',
    },
  };
  const wrapperCol = {
    span: 14,
  };
  // ---------------密码修改字段----------------------
  const passwordFormState = reactive({
    username: '',
    displayName: '',
    password: '',
    newpassword: '',
    id: '',
    userId: '',
    switch_status: true,
  });
  // 密码修改
  const visible1 = ref(false);
  async function modify() {
    if (selectRecords.value.length > 0) {
      let aresname = { ...selectRecords.value[selectRecords.value.length - 1] };
      passwordFormState.username = aresname.username;
      passwordFormState.displayName = aresname.displayName;
      // 把id里面的值数组字符串转化数字
      passwordFormState.id = selectedRowKeyList.value[0];
      // 把userId里面的值数组字符串转化数字
      passwordFormState.userId = selectedRowKeyList.value[0];
      visible1.value = true;
    }
  }
  // 用于存储可能出现的错误信息
  // 密码生成
  async function generatePassword(param) {
    try {
      const response = await userApi.getPasswordFetch(param);
      passwordFormState.newpassword = response.data;
      passwordFormState.password = response.data;
    } catch (error) {}
  }
  //密码修改框提交
  async function handleOk() {
    const reschange = await userApi.getchangeFetch(passwordFormState);
    if (reschange.code === 0) {
      message.success('密码修改提交成功');
      visible1.value = false;
    }
  }
  // 密码重置
  const passwordReset = async () => {
    // 把两个参数传到后端去
    let obj = {
      userId: selectedRowKeyList.value[0],
      username: selectRecords.value[0].username,
    };
    try {
      const response = await userApi.getresetFetch(obj);
      if (response.code === 0) {
        message.success('密码重置成功');
      } else {
        alert('密码重置失败' + response.data.message);
      }
    } catch (error) {
      alert('密码重置失败' + error.message);
    }
  };
  // --------------------------- 查询 ---------------------------
  const queryFormState = {
    pageNumber: 1,
    pageSizeOptions: '',
    startDate: '',
    endDatePicker: '',
    startDatePicker: '',
    endDate: '',
    departmentId: '',
    username: '',
    displayNam: '',
    pageSize: 10,
    pageNumber: current.value,
    searchCount: true,
  };
  const queryForm = reactive({ ...queryFormState });
  const total = ref(0);
  const pageSizeOptions = ref(['10', '20', '30', '40', '50']);
  const onShowSizeChange = (current, pageSize) => {
    pageSizeRef.value = Number(pageSize);
    queryTable();
  };
  // 编辑弹框
  const formState = reactive({
    // --------------------------------------------------基础信息
    displayName: '', //姓名
    username: '', //登录账号
    gender: 2, //性别
    employeeNumber: '', //员工编号
    userType: '', //用户类型
    email: '', //电子邮箱
    windowsAccount: '', //域账号
    userState: '', //用户状态
    online: '', //状态
    password: '123456', //密码
    //--------------------------------------------------个人信息
    familyName: '', //姓
    middleName: '', //中间名
    givenName: '', //名
    nickName: '', //昵称
    idType: '', //证件类型
    idCardNo: 0, //证件号码
    married: '', //婚姻状态
    education: '', //学历
    graduateFrom: '', //毕业院校
    graduateDate: '', //毕业时间
    startWorkDate: '', //工作时间
    webSite: '', //个人主页
    preferredLanguage: '', //语言偏好
    timeZone: '', //时区
    definelm: '', //即时通讯
    //---------------------------------------------------机构信息
    organization: '', //所属组织
    division: '', //分支机构
    departmentId: '', //部门编号
    department: '', //部门名称
    jobTitle: '', //职位
    assistant: '', //助理
    manager: '', //上级经理
    entryDate: '', //入职时间
    quitDate: '', //离职时间
    costCenter: '', //成本中心
    jobLevel: '', //级别
    workOfficeName: '', //办公地址
    //-----------------------------------------------机构扩展
    workPhoneNumber: '', //工作电话
    workEmail: '', //工作邮件
    homeCountry: '', //国家
    workRegion: '', //省
    workLocality: '', //城市
    homeLocality: '', //城市
    workFax: '', //传真
    homeRegion: '',
    workStreetAddress: '',
    //----------------------------------------------家庭信息
    homeEmail: '', //家庭邮箱
    homePhoneNumber: '', //家庭电话
    homeFax: '', //家庭传真
    homePostalCode: '', //家庭编码
    homeStreetAddress: '', //家庭地址
  });
  const expandedKeys = ref(['1', '1-2']);
  const selectedKeys = ref([]);
  // 下载模板
  async function confirmBatchDelete() {
    await userApi.usersDownload();
  }
  //导出
  async function onExportGoods() {
    await userApi.exportDownloadUser();
  }
  const useToken = localRead(LocalStorageKeyConst.USER_TOKEN);
  const headers = {
    authorization: 'Bearer ' + useToken,
    Token: useToken,
    authserver: 'MaxKey',
  };
  const handleChange = (info) => {
    if (info.file.status !== 'uploading') {
      console.log(info.file, info.fileList);
    }
    if (info.file.status === 'done') {
      queryDepartmentTree();
      queryTable();
      message.success(`${info.file.name} 导入成功`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 导入失败`);
    }
  };
  // 部门名称
  async function queryTree() {
    let res = await userApi.getOrgsTree(queryForm);
    departmentOptions.value = res.data.nodes.map((item) => {
      return {
        label: item.title,
        value: item.key,
      };
    });
  }
  // 主页列表查询
  async function queryTable() {
    let res = await userApi.getOrgsFetch(queryForm);
    dataSource.value = res.data.rows; //查询
    total.value = res.data.records;
  }
  // 分页
  const onPageChange = (page) => {};
  const activeKey = ref('1'); //导航标签默认第一页

  const columns = [
    {
      title: '登录账号',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '姓名',
      dataIndex: 'displayName',
      key: 'displayName',
    },
    {
      title: '员工编号',
      dataIndex: 'employeeNumber',
      key: 'employeeNumber',
    },
    {
      title: '部门名称',
      dataIndex: 'department',
      key: 'department',
    },
    {
      title: '性别',
      dataIndex: 'gender',
      key: 'gender',
    },
    {
      title: '状态',
      key: 'action',
    },
    {
      title: '操作',
      dataIndex: 'status',
      // fixed: 'right',
      key: 'status',
      width: 150,
    },
  ];
  const rules = {
    // 用户类型
    userType: [
      {
        required: true,
        message: '请选择用户类型',
        trigger: 'change',
      },
    ],
    // 用户状态
    userState: [
      {
        required: true,
        message: '请选择用户状态',
        trigger: 'change',
      },
    ],
    // 状态
    online: [
      {
        required: true,
        message: '请选择状态',
        trigger: 'change',
      },
    ],
  };
  // -------------------------操作---------------------
  // 账号
  const router = useRouter();
  function accounts() {
    router.push('../system/accountment');
  }
  // 岗位
  const open = ref(false);
  const showModal = () => {
    open.value = true;
    queryTable2();
  };
  const handleOk3 = (e) => {
    open.value = false;
  };
  const formStatePositions = reactive({
    Positionname: '',
    Positionregion: '',
    ids: '',
    postName: '',
    displayName: '',
    departmentId: '',
    userId: '',
    username: '',
    assign: 'owns',
    startDate: '',
    endDate: '',
    startDatePicke: '',
    endDatePicker: '',
    pageSize: 5,
    pageNumber: current.value,
    pageSizeOptions: 5,
    pageSizeOptions: 10,
    pageSizeOptions: 20,
  });
  const total2 = ref(0);
  const pageSizeOptions2 = ref(['10', '20', '30', '40']);
  const onShowSizeChange2 = (current, pageSize) => {
    pageSizeRef.value = Number(pageSize);
    queryTable2();
  };
  // 弹框表格分页
  const onPageChange2 = (page) => {
    queryTable2();
  };
  const columnss = [
    {
      title: '岗位编码',
      dataIndex: 'postCode',
      key: 'postCode',
    },
    {
      title: '岗位名称',
      dataIndex: 'postName',
      key: 'postName',
      width: 90,
    },
    {
      title: '部门编码',
      dataIndex: 'departmentId',
      key: 'departmentId',
    },
    {
      title: '部门名称',
      dataIndex: 'department',
      key: 'department',
    },
    {
      title: '状态',
      dataIndex: 'instId',
      key: 'instId',
      width: 70,
    },
    {
      title: '操作',
      dataIndex: 'statuss',
      key: 'statuss',
      fixed: 'right',
    },
  ];
  //
  const handleSelectChange = (value) => {
    formStatePositions.assign = value;
  };
  // 操作岗位表格新增
  const handleAdd = async () => {
    let addres = await userApi.getpostaddFetch(formStatePositions);
    if (addres.code === 0) {
      message.success('新增成功');
      queryTable2();
    }
  };
  // 操作岗位表格删除
  const handleEditor = async (value) => {
    Modal.confirm({
      title: () => '确定要删除吗?',
      content: () => '删除后不可恢复',
      onOk() {
        userApi
          .getdeleteapi(value)
          .then((res) => {
            if (res.code === 0) {
              message.success('删除成功');
              queryTable2();
            } else {
              message.success('删除失败');
            }
          })
          .catvh(error('请求失败'));
        console.log(error);
      },
      onCancel() {},
    });
  };
const dataSources = ref([]);
  // 表格查询
  async function queryTable2() {
    let positionsres = await userApi.getPositionsFetch(formStatePositions);
    // 表格数据
    dataSources.value = positionsres.data.rows;
    // 分页
    total2.value = positionsres.data.records;
  }
  // 兼职
  const ParttimeformRef = ref(false);
  const parttime = () => {
    ParttimeformRef.value.showModal();
  };
  // 锁定
  async function locks(record) {
    console.log(record.status);
    let objectid = {
      id: record.id,
      status: 5,
    };
    let lockscagres = await userApi.updateStatus(objectid);
    console.log(lockscagres);
    if (lockscagres.code === 0) {
      message.success('锁定成功');
    }
    queryTable();
  }
  // 解锁
  async function unlock(record) {
    let objectid = {
      id: record.id,
      status: 1,
    };
    let unlockResult = await userApi.updateStatus(objectid);
    console.log(unlockResult);
    if (unlockResult.success || unlockResult.code === 0) {
      message.success('解锁成功');
    }
    queryTable();
  }
  // 禁用
  async function Disables(record) {
    console.log(record);
    let objectid = {
      id: record.id,
      status: 4,
    };
    console.log(objectid);

    let lockscagres = await userApi.updateStatus(objectid);
    console.log(lockscagres);
    if (lockscagres.success || lockscagres.code === 0) {
      message.success('禁用成功');
    }
    queryTable();
  }
  // 启用
  async function unlocks(record) {
    let objectid = {
      id: record.id,
      status: 1,
    };
    let unlockResult = await userApi.updateStatus(objectid);
    console.log(unlockResult);
    if (unlockResult.success || unlockResult.code === 0) {
      message.success('启用成功');
    }
    queryTable();
  }
  // --------------------新增 删除 编辑-----------------------------------
  // 打开新增框且清空表单数据
  const add = () => {
    title.value = '添加';
    visible.value = true;
    formState.departmentId = '';
    formState.email = '';
    formState.username = '';
    formState.displayName = '';
    formState.gender = '';
    formState.employeeNumber = '';
    formState.userType = '';
    formState.email = '';
    formState.windowsAccount = '';
    formState.userState = '';
    formState.online = '';
    formState.familyName = '';
    formState.middleName = '';
    formState.givenName = '';
    formState.nickName = '';
    formState.idType = '';
    formState.idCardNo = '';
    formState.married = '';
    formState.education = '';
    formState.graduateFrom = '';
    formState.graduateDate = '';
    formState.startWorkDate = '';
    formState.webSite = '';
    formState.preferredLanguage = '';
    formState.timeZone = '';
    formState.definelm = '';
    formState.organization = '';
    formStatedivision = '';
    formState.departmentId = '';
    formState.department = '';
    formState.jobTitle = '';
    formState.assistant = '';
    formState.manager = '';
    formState.entryDate = '';
    formState.quitDate = '';
    formState.costCenter = '';
    formState.workOfficeName = '';
    formState.workPhoneNumber = '';
    formState.workEmail = '';
    formState.homeCountry = '';
    formState.workRegion = '';
    formState.workLocality = '';
    formState.homeLocality = '';
    formState.workFax = '';
    formState.homeRegion = '';
    formState.workStreetAddress = '';
    formState.homeEmail = '';
    formState.homePhoneNumber = '';
    formState.homeFax = '';
    formState.homePostalCode = '';
    formState.homeStreetAddress = '';
  };
  const formRef1 = ref(null);
  //表格表单提交
  const handleOk2 = (e) => {
    formRef1.value
      .validate()
      .then(() => {
        formStateadd(formState);
      })
      .catch((error) => {});
  };
  //(delete formState.givenName;)如果这个字段为空调用接口是就把它从字段删除
  async function formStateadd(formState) {
    if (formState.givenName == '') {
      delete formState.givenName;
    }
    if (formState.displayName == '') {
      delete formState.displayName;
    }
    if (formState.username == '') {
      delete formState.username;
    }
    if (formState.gender == '') {
      delete formState.gender;
    }
    if (formState.employeeNumber == '') {
      delete formState.employeeNumber;
    }
    if (formState.userType == '') {
      delete formState.userType;
    }
    if (formState.email == '') {
      delete formState.email;
    }
    if (formState.windowsAccount == '') {
      delete formState.windowsAccount;
    }
    if (formState.userState == '') {
      delete formState.userState;
    }
    if (formState.online == '') {
      delete formState.online;
    }
    if (formState.familyName == '') {
      delete formState.familyName;
    }
    if (formState.middleName == '') {
      delete formState.middleName;
    }
    if (formState.nickName == '') {
      delete formState.nickName;
    }
    if (formState.idType == '') {
      delete formState.idType;
    }
    if (formState.idCardNo == '') {
      delete formState.idCardNo;
    }
    if (formState.married == '') {
      delete formState.married;
    }
    if (formState.education == '') {
      delete formState.education;
    }
    if (formState.graduateFrom == '') {
      delete formState.graduateFrom;
    }
    if (formState.graduateDate == '') {
      delete formState.graduateDate;
    }
    if (formState.startWorkDate == '') {
      delete formState.startWorkDate;
    }
    if (formState.webSite == '') {
      delete formState.webSite;
    }
    if (formState.preferredLanguage == '') {
      delete formState.preferredLanguage;
    }
    if (formState.timeZone == '') {
      delete formState.timeZone;
    }
    if (formState.definelm == '') {
      delete formState.definelm;
    }
    if (formState.organization == '') {
      delete formState.organization;
    }
    if (formState.division == '') {
      delete formState.division;
    }
    if (formState.departmentId == '') {
      delete formState.departmentId;
    }
    if (formState.jobTitle == '') {
      delete formState.jobTitle;
    }
    if (formState.assistant == '') {
      delete formState.assistant;
    }
    if (formState.jobLevel == '') {
      delete formState.jobLevel;
    }
    if (formState.entryDate == '') {
      delete formState.entryDate;
    }
    if (formState.quitDate == '') {
      delete formState.quitDate;
    }
    if (formState.costCenter == '') {
      delete formState.costCenter;
    }
    if (formState.manager == '') {
      delete formState.manager;
    }
    if (formState.workOfficeName == '') {
      delete formState.workOfficeName;
    }
    if (formState.workPhoneNumber == '') {
      delete formState.workPhoneNumber;
    }
    if (formState.workEmail == '') {
      delete formState.workEmail;
    }
    if (formState.homeCountry == '') {
      delete formState.homeCountry;
    }
    if (formState.workRegion == '') {
      delete formState.workRegion;
    }
    if (formState.workLocality == '') {
      delete formState.workLocality;
    }
    if (formState.homeLocality == '') {
      delete formState.homeLocality;
    }
    if (formState.homePhoneNumber == '') {
      delete formState.homePhoneNumber;
    }
    if (formState.homeEmail == '') {
      delete formState.homeEmail;
    }
    if (formState.homeFax == '') {
      delete formState.homeFax;
    }
    if (formState.homePostalCode == '') {
      delete formState.homePostalCode;
    }
    if (formState.homeStreetAddress == '') {
      delete formState.homeStreetAddress;
    }
    if (formState.homeRegion == '') {
      delete formState.homeRegion;
    }

    // 添加
    if (title.value === '添加') {
      const res = await userApi.getOrgsAdd(formState);
      if (res.code === 0) {
        message.success('添加成功');
        queryTable();
        visible.value = false;
      }
      // 编辑
    } else if (title.value === '编辑') {
      const res1 = await userApi.puteaitupdate(formState);
      if (res1.code === 0) {
        message.success('修改成功');
        queryTable();
        visible.value = false;
      }
    }
  }
  // 编辑框
  const visible = ref(false);
  // 打开编辑框+数据回显
  const edit = async (record) => {
    title.value = '编辑';
    visible.value = true;
    let res = await userApi.geteaitFetch(record.id);
    console.log(res.data);
    Object.assign(formState, res.data);
  };
  // 删除
  async function deletes(record) {
    let ress = await userApi.getdeleteFetch({ ids: record ? record.id : selectedRowKeyList.value.join(',') });
    if (ress.code === 0) {
      message.success('删除成功');
      queryTable();
    }
  }
  const okButtonText = '提交';
  const cancelButtonText = '关闭';

  onMounted(() => {
    queryDepartmentTree();
    queryTable();
    queryTree();
  });
  // ----------------------查询部门列表并构建 部门树----------------------------
  async function queryDepartmentTree() {
    let res = await userApi.getOrgsTree();
    treeData.value = buildTree(res.data.nodes);
  }
  function treeSelectChange(idList) {
    const stringId = idList.join('');
    queryForm.departmentId = stringId;
    queryTable();
  }
  function buildTree(data) {
    const tree = [];
    const map = {};
    // 先把所有节点放入一个映射表
    data.forEach((item) => {
      map[item.key] = { title: item.title, key: item.key, parentKey: item.parentKey, children: [] };
    });
    // 构建树
    data.forEach((item) => {
      const { parentKey } = item;
      if (parentKey === '0') {
        // 如果是根节点
        tree.push(map[item.key]);
      } else {
        // 如果有父节点，则将当前节点添加到父节点的children中
        if (map[parentKey]) {
          map[parentKey].children.push(map[item.key]);
        }
      }
    });
    return tree;
  }
  // 跳转角色页面
  function toRoles(record) {
    router.push({ path: '/access/rolemembers', query: { memberName: record.displayName, userId: record.id } });
  }
</script>

<style scoped lang="less">
  .avatar-uploader > .ant-upload {
    width: 128px;
    height: 128px;
  }
  .ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }
  .smart-table-operate-block {
    .ant-btn {
      margin: 0 12px 8px 0;
    }
  }
  .height100 {
    height: 100%;
  }

  .help-doc-box {
    display: flex;
    flex-direction: column;

    .employee {
      flex-grow: 2;
      margin-top: 10px;
    }
  }

  .tree-container {
    height: 100%;

    .tree {
      height: 618px;
      margin-top: 10px;
      overflow-x: hidden;
    }

    .sort-flag-row {
      margin-top: 10px;
      margin-bottom: 10px;
    }

    .sort-span {
      margin-left: 5px;
    }

    .no-data {
      margin: 10px;
    }
  }
</style>
